<template>
	<view>
		<u-button type="primary" v-if="loginCode.countDownNumber == 60" :custom-style="loginCode.customStyle"
			:plain="true">获取验证码 </u-button>
		<u-button type="primary" v-else :custom-style="loginCode.customStyle" :plain="true"
			:disabled="loginCode.text!='重新发送'">
			{{ loginCode.text }}
		</u-button>
	</view>
</template>
<script setup>
	import {
		ref,
		reactive
	} from "vue";
	import {
		mobileCheck,
		msg
	} from "@/utils/common";
	import {
		sendCode
	} from "@/api/module/login";
	const loginCode = reactive({
		text: '获取验证码',
		countDownNumber: 60,
		isStart: false,
		interval: null,
		sendCode: (cellphone, type) => {
			if (!cellphone) {
				return msg('请输入手机号');
			}
			if (!mobileCheck(cellphone)) {
				return msg('手机号格式有误');
			}
			if (loginCode.isStart) return
			sendCode({
				mobile: cellphone,
				type: type || 'login_code',
			}).then(res => {
				console.log(res);
				loginCode.countDown()
			})
		},
		clear: () => {
			loginCode.countDownNumber = 60
			loginCode.text = '重新发送'
			loginCode.isStart = false
			clearInterval(loginCode.interval)
		},
		countDown: () => {
			loginCode.countDownNumber = 60;
			loginCode.isStart = true
			loginCode.interval = setInterval(() => {
				if (loginCode.countDownNumber == 1) {
					loginCode.text = '重新发送'
					loginCode.isStart = false
					clearInterval(loginCode.interval)
					return
				}
				loginCode.countDownNumber--
				loginCode.text = `${loginCode.countDownNumber}″`
			}, 1000)
		},
		customStyle: {
			padding: 0,
			width: "180rpx",
			height: "64rpx",
			// background: '#4787F0',
			borderRadius: '8rpx',
			// color: '#fff',
			fontSize: '28rpx',
			marginRight: '10rpx',
			textAlign: 'center'
		},
	});
	const send = (data) => {
		loginCode.sendCode(data.phone, data.type)
	}
	defineExpose({
		send
	});
</script>